package com.mankiw.code_generator.service.impl;

import com.mankiw.code_generator.entity.DataSource;
import com.mankiw.code_generator.repository.IDataSourceRepository;
import com.mankiw.code_generator.service.IDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Optional;

@Service
public class DataSourceService implements IDataSourceService {

    @Autowired
    IDataSourceRepository repository;

    @Override
    public DataSource add(DataSource dataSource){
        createDataSource(dataSource);

        DataSource result = repository.save(dataSource);
        return result;
    }

    @Override
    public DataSource findById(Long id) {
        var result = repository.findById(id).get();
        return result;
    }

    private static void createDataSource(DataSource dataSource) {
        try {
            Connection connection = DriverManager
                    .getConnection(
                            dataSource.getAddress(),
                            dataSource.getUserName(),
                            dataSource.getPassword()
                    );
            var resultSet = connection.getMetaData().getCatalogs();
            var isExist = false;
            while (resultSet.next()) {
                if (dataSource.getDatabaseName().equals(resultSet.getString(1))) {
                    isExist = true;
                }
            }
            if (!isExist) {
                Statement stmt = connection.createStatement();
                stmt.executeUpdate("create database " + dataSource.getDatabaseName());
                stmt.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
